<template>
  <el-dialog
    v-el-drag-dialog
    :title="'等级设定'"
    :visible.sync="visible"
    width="1440px"
    @closed="reset"
  >
    <div class="main">
      <h3>{{ temp.levelName }}</h3>
      <div class="pageItem">
        <h5><i style="font-size: 16px;" class="el-icon-s-marketing" /> 升级条件</h5>
        <span class="spanItem">满足以下条件将成为{{ temp.levelName }}&emsp;</span>
        <el-switch
          v-model="switchValue"
          disabled
          active-color="#13ce66"
          inactive-color="#ff4949"
        />
        <span v-if="!switchValue" class="spanItem border0">您未开启{{ temp.levelName }}升级策略，本等级会员将不参与升降级</span>
      </div>
      <div v-if="switchValue" style="display: flex;">
        <el-checkbox-group v-model="checkList" disabled @change="changeCheckeList">
          <el-checkbox label="1">居民用户</el-checkbox>
          <el-checkbox label="2">商业用户</el-checkbox>
          <el-checkbox label="4">工业用户</el-checkbox>
          <el-checkbox label="8">瓶批用户</el-checkbox>
          <el-checkbox label="16">槽批用户</el-checkbox>
        </el-checkbox-group>
        <el-checkbox-group v-model="checkList2" disabled style="margin-left: 8px;" @change="changeCheckeList2">
          <el-checkbox label="3">仅限绑定钢瓶的客户</el-checkbox>
        </el-checkbox-group>
      </div>
      <div v-if="switchValue" style="display: flex; align-items: center;">
        一个自然月内,购气瓶数
        <el-input v-model="temp.limit1" disabled size="mini" style="width: 60px;" />
        <span v-if="!checkList2.length">或&nbsp; 消费金额￥</span>
        <el-input v-if="!checkList2.length" v-model="temp.limit2" disabled size="mini" style="width: 60px;" />
        <span v-if="!checkList2.length">或&nbsp;用气量</span>
        <el-input v-if="!checkList2.length" v-model="temp.limit3" disabled size="mini" style="width: 60px;" />
      </div>
      <div class="pageItem">
        <h5><i style="font-size: 16px;" class="el-icon-s-finance" /> 等级权益</h5>
        <span class="spanItem border0">{{ temp.levelName }}可享受的商品权益</span>
      </div>
      <div class="goodsTitle">
        <div v-if="type=='edit'">
          <el-button type="primary" class="append-search" @click="addGoods">添加</el-button>
        </div>
        <div style="width: 20px; color: red; text-align: center;">
          *
        </div>
        <div>
          <p>设定上限的商品将在微信端每月1号赠送相应金额的优惠券，可在下单时使用，每个商品对应一张，可叠加；</p>
          <p>未设上限的商品下单时直接按优惠价结算；</p>
        </div>
      </div>
      <lb-table
        ref="lbTable"
        border
        highlight-current-row
        element-loading-text="加载中"
        height="200"
        :column="tableData.column"
        :data="tableData.data"
        :total="tableData.total"
        custom-column
      />
      <div class="pageItem">
        <h5><i style="font-size: 16px;" class="el-icon-s-finance" /> 适用渠道</h5>
        <span class="spanItem border0">{{ temp.levelName }}权益适用的下单渠道</span>
      </div>
      <el-checkbox-group v-model="checkList3" style="margin-left: 8px;">
        <el-checkbox label="3">微信</el-checkbox>
      </el-checkbox-group>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="reset">
        关闭
      </el-button>
      <!-- <el-button :loading="$loadingPlugin.add || $loadingPlugin.edit" type="primary" @click="success">
        保存
      </el-button> -->
    </div>
  </el-dialog>
</template>

<script>
  import { LevelHistory, goodsTypeQueryList, goodsTypeDetail, LevelGoodsPrice, customerLevelEquityDetail } from '@/api'
  // import { parseTime } from '@/utils'

  export default {
    name: 'lookLast',
    data() {
      return {
        visible: false,
        switchValue: false,
        checked: false,
        checkList: [],
        checkList2: [],
        checkList3: [],
        goodsTypes: [], // 商品分类
        goodsTypesDetailList: [], // 商品分类详情
        goodsDiscountList: [{ 'value': 1, 'desc': '减免', 'key': 'JM' }, { 'value': 2, 'desc': '折扣', 'key': 'ZK' }, { 'value': 3, 'desc': '固定', 'key': 'GD' }], // 商品优惠类型
        tableData: {
          total: 0,
          column: [
            { label: '商品分类', prop: 'gtName', width: 200, align: 'center',
              render: (h, { row, $index, column }) => {
                return (
                <div>
                  {(<span >{row[column.property]}</span>)}
                </div>
              )
              }
            },

            { label: '商品名称', prop: 'goodsName', width: 200, align: 'center',
              render: (h, { row, $index, column }) => {
                return (
                <div>
                  {(<span >{row[column.property]}</span>)}
                </div>
              )
              }
            },
            { label: '规格型号', prop: 'specName', width: 100, align: 'center'
              // render: (h, { row }) => <span>{ row.modifyTime && parseTime(row.modifyTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            { label: '优惠类型', prop: 'disType', width: 100, align: 'center',
              render: (h, { row, $index, column }) => {
                return (
                <div>
                  { (<span >{row[column.property] && this.goodsDiscountList.find(l => l.value * 1 === row[column.property] * 1).desc}</span>)}
                </div>
              )
              }
            },
            { label: '权益数值', prop: 'discount', width: 200, align: 'center',
              render: (h, { row, $index, column }) => {
                return (
                <div>
                  {(<span >{row[column.property] ? (row[column.property] * 1).toFixed(2) : ''}</span>)}
                </div>
              )
              }
            },
            { label: '挂牌价(￥)', prop: 'price1', width: 200, align: 'center'
            },
            { label: '优惠价(￥)', prop: 'price2', width: 200, align: 'center'
            },
            { label: '优惠上限(单位/月)', prop: 'disLimit', width: 200, align: 'center',
              render: (h, { row, $index, column }) => {
                return (
                <div>
                  {(<span >{row[column.property] ? row[column.property] * 1 : '' }</span>)}
                </div>
              )
              }
            }
          ],
          data: []
        },

        type: 'add',
        temp: {

        },
        rules: {
          // csmPhone: [{ required: true, message: '请输入', trigger: 'change' }],
          // csmName: [{ required: true, message: '请输入用户编码', trigger: 'change' }],
          // orderCode: [{ required: true, message: '请输入押金单号', trigger: 'change' }],
          // address: [{ required: true, message: '请选择投保地址', trigger: 'change' }],
          // price: [{ required: true, message: '请输入投保金额', trigger: 'change' }]
        }
      }
    },
    mounted() {
      this.getGoodsTypes()
      // this.$watch('checkList2', (val) => {
      //   console.log(val)
      // })
    },
    methods: {
      reset() {
        this.visible = false
        this.temp = {

        }
        this.$nextTick(() => {
          this.tableData.data = []
          this.switchValue = false
          this.checkList2 = []
          this.checkList = []
          this.checkList = []
          // this.$refs.dataForm.clearValidate()
        })
      },
      // 表格数据
      async getgoods() {
        try {
          console.log(this.type, 'type111')
          if (this.type === 'detail') {
            var rlt = await customerLevelEquityDetail({ levelNum: this.temp.levelNum })
          } else if (this.type === 'last') {
            rlt = await LevelHistory({ levelNum: this.temp.levelNum })
          }
          // /表格处理开始
          if (rlt.exc != null) {
            this.$message.error('查询异常\t' + rlt.exc)
            return
          } else if (!rlt.data) { // 说明当前等级权限不存在
            return
          }
          // 当前等级权限存在
          var customerLevelEquityBean = rlt.data
          // 查询开关是否打开
          if ((customerLevelEquityBean.levelOptions & 0x01) > 0) { // 说明开关打开
            this.switchValue = true
            // 判断 仅限绑定钢瓶的客户开关是否勾选
            if ((customerLevelEquityBean.levelOptions >> 1 & 0x01) > 0) { // 说明开关勾选
              this.checkList2 = ['3']// 绑定钢瓶客户
            } else { // 判断居民用户 商业用户 工业用户 瓶批用户 槽批用户选中情况
              if ((customerLevelEquityBean.csmTypeOptions & 0x01) > 0) { // 说明开关打开
                this.checkList.push('1') // 居民
              }

              // 判断 商业用户是否勾选
              if ((customerLevelEquityBean.csmTypeOptions >> 1 & 0x01) > 0) { // 说明开关打开
                this.checkList.push('2') // 商业
              }

              // 判断 工业用户是否勾选
              if ((customerLevelEquityBean.csmTypeOptions >> 2 & 0x01) > 0) { // 说明开关打开
                this.checkList.push('4') // 工业
              }

              // 判断 瓶批用户是否勾选
              if ((customerLevelEquityBean.csmTypeOptions >> 3 & 0x01) > 0) { // 说明开关打开
                this.checkList.push('8') // 瓶批
              }

              // 判断 槽批用户是否勾选
              if ((customerLevelEquityBean.csmTypeOptions >> 4 & 0x01) > 0) { // 说明开关打开
                this.checkList.push('16')// 槽批
              }
            }
            // 回填购气瓶数
            if (customerLevelEquityBean.limit1 !== 0) {
              // _this.limit1.numberbox('setValue', customerLevelEquityBean.limit1)
              if (customerLevelEquityBean.limit2 === 0 && customerLevelEquityBean.limit3 === 0) {
                // $('#detailLevel_win_limit1_span_span').css('display', 'none')
              }
            } else {
              this.temp.limit1 = null
              // $('#detailLevel_win_limit1_span').hide()
            }
            // 回填消费金额
            if (customerLevelEquityBean.limit2 !== 0) {
              this.temp.limit2 = customerLevelEquityBean.limit2 / 100
              // _this.limit2.numberbox('setValue', customerLevelEquityBean.limit2 / 100)
              if (customerLevelEquityBean.limit3 === 0) {
                // $('#detailLevel_win_limit2_span_span').css('display', 'none')
              }
            } else {
              this.temp.limit2 = null
            }

            // 回填用户量
            if (customerLevelEquityBean.limit3 !== 0) {
              this.temp.limit3 = customerLevelEquityBean.limit3 / 1000
            } else {
              // $('#detailLevel_win_limit3_span').hide()
            }
          } else {
            // $('#detailLevel_win_span').show()
            // $('#detailLevel_win_div').hide()
          }
          // 回填适用渠道 从右往左 第一位是呼叫中心 第二位是微信
          if ((customerLevelEquityBean.platOptions >> 1 & 0x01) > 0) { // 说明微信渠道勾选了
            this.checkList3 = ['3']
            // $('#detailLevel_win_platOptions1').prop('checked', true)
          }

          // 回填商品表格
          // var detailList = customerLevelEquityBean.detailList
          // for (var i = 0; i < detailList.length; i++) {
          //   var bean = detailList[i]
          //   bean.isEdit = true // 说明是编辑
          //   _this.table.datagrid('appendRow', bean)
          // }
          // /表格处理结束
          this.tableData.data = rlt.data.detailList

          if (this.tableData.data.length) {
            this.tableData.data.forEach(l => {
              // l.discount = l.discount / 100
              // LevelGoodsPrice
              this.selectGoodsBasePrice(l)
            })
          }
        } catch (error) {
          console.log(error)
        }
      },
      async selectGoodsBasePrice(row) {
        // 查询挂牌价,计算优惠价
        const rlt = await LevelGoodsPrice({ goodsId: row.goodsId })
        if (rlt.exc != null) {
          this.$message.error(rlt.exc)
          return
        }
        var goodsInfo = rlt.data
        if (!goodsInfo.basePrice) {
          this.$message.error('当前商品不存在挂牌价')
          return
        }
        row.price1 = goodsInfo.basePrice
        var discount = row.discount
        discount = this.toDecimal(discount / 100, 2)
        row.discount = discount
        // 计算优惠价
        if (row.disType === 1) { // 减免
          var price2Value = (this.toDecimal(row.price1, 2)) - (this.toDecimal(discount, 2))
          row.price2 = this.toDecimal(price2Value, 2) // 计算优惠价
        }
        if (row.disType === 2) { // 折扣
          if (this.toDecimal(discount, 2) > 1) {
            row.discount = ''
            row.price2 = ''
            this.$message.error('优惠类型为折扣,权限数值不能大于1')
            return
          }

          price2Value = row.price1 * (this.toDecimal(discount, 2))
          row.price2 = this.toDecimal(price2Value, 2) // 计算优惠价
        }

        if (row.disType === 3) { // 固定
          row.price2 = row.discount
        }

        // _this.table.datagrid('updateRow', row)
        // _this.table.datagrid('refreshRow', _this.table.datagrid('getRowIndex', row))
        // $dlh.cmct.post({
        //   url: 'page/sys/price/select/goodsInfoBasePriceByGoodsId',
        //   data: {
        //     goodsId: row.goodsId
        //   }
        // }, function(rlt) {

        // })
      },
      toDecimal(str, p) {
        var reg = /^(-?\d+)(\.\d+)?$/
        if (reg.test(str)) {
          return parseFloat(str).toFixed(p || 2) * 1
        }
        return 0
      },
      // 商品分类的onchange事件
      changeGoodsType(row, column, value) {
        console.log(value)
        var text = event.target.innerText
        row[column.property] = text
        this.tableData.data = [...this.tableData.data]
        this.getGoodsTypeDetails(value)
      },
      // 商品分类详情的onchange事件
      changeGoodsName(row, column, value) {
        console.log(value)
        var text = event.target.innerText
        console.log(event)
        row[column.property] = text
        this.tableData.data = [...this.tableData.data]
      },
      // 商品优惠类型的onChange事件
      changeDiscount(row, column, value) {
        console.log(value)
        // var text = event.target.innerText
        // console.log(event)
        row[column.property] = value
        this.tableData.data = [...this.tableData.data]
      },
      // 权益数值input事件
      changeInput(row, column, value) {
        row[column.property] = value

        // const reg = /^(-?\d+)(\.\d+)?$/
        // console.log(value)
        // console.log(reg.test(value))
        // if (reg.test(value)) {
        //   row[column.property] = value
        //   // this.tableData.data = [...this.tableData.data]
        // } else {
        //   row[column.property] = value

        //   // row[column.property] = ''
        // }
      },
      // 获取商品分类详情
      async getGoodsTypeDetails(val) {
        try {
          const res = await goodsTypeDetail({ gtId: val })
          this.goodsTypesDetailList = res.data.rows
        } catch (error) {
          console.log(error)
        }
      },
      handleEdit(row, $index) {
        this.$set(row, '_edit', true)
      },
      handleSave(row, $index) {
        const reg = /^(-?\d+)(\.\d+)?$/
        if (!reg.test(row.discount)) {
          this.$message.warning('权益数值只能为数值')
          return
        }
        if (!reg.test(row.disLimit)) {
          this.$message.warning('优惠上限只能为数值')
          return
        }
        this.$set(row, '_edit', false)
        this.$set(this.tableData.data, $index, JSON.parse(JSON.stringify(row)))
      },
      // 获取商品类型
      async getGoodsTypes() {
        try {
          const res = await goodsTypeQueryList()
          this.goodsTypes = res.data
          console.log(res)
        } catch (e) {
          console.log(e)
        }
      },
      // 删除商品
      del(row, index) {
        this.tableData.data.splice(index, 1)
      },
      // 添加商品
      addGoods() {
        this.tableData.data.push({ discount: '', disLimit: '' })
        this.tableData.data = [...this.tableData.data]
      },
      changeCheckeList(val) {
        if (val) {
          this.checkList2 = []
        }
      },
      changeCheckeList2(val) {
        if (val) {
          this.checkList = []
        }
      },
      open(temp) {
        return new Promise(resolve => {
          this.resolve = resolve
          this.type = temp.type
          this.visible = true
          if (temp) {
            this.temp = Object.assign({ ...this.temp }, { ...temp })
            this.getgoods()
          }
        })
      },
      success() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          if (this.type === 'add') {
            this.add()
          } else {
            this.edit()
          }
        })
      },
      async add() {
        // await roleAdd(this.temp)
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '新增成功',
          type: 'success',
          duration: 2000
        })
      },
      async edit() {
        // await roleUpdate(this.temp)
        this.resolve(this.temp)
        this.visible = false
        this.$notify({
          title: '提示',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
      }

    }
  }
</script>

<style lang="scss" scoped>
.main {
  h3,
  h5 {
    padding: 0;
    margin: 8px 0;
    box-sizing: border-box;
  }
  div {
    margin: 8px 0;
    box-sizing: border-box;
  }
  .pageItem {
    display: flex;
    align-items: center;
    font-size: 18px;
    h5 {
      display: inline-block;
      height: 26px;
      line-height: 26px;
      border-bottom: 1px solid #eee;
    }
    .spanItem {
      display: inline-block;
      height: 26px;
      font-size: 14px;
      line-height: 25px;
      color: gray;
      text-indent: 1em;
      border-bottom: 1px solid #eee;
      box-sizing: border-box;
    }
    .border0 {
      border: 0;
    }
  }
  .goodsTitle {
    display: flex;
    color: red;
  }
}
.none {
  display: none;
}
</style>
